#include "chess.h"


Chess::Chess()
{
    chess_head = new chess_t{0, 0, ChessNull, nullptr, nullptr};
    chess_head->next = chess_head;
    chess_head->pre = chess_head;
}

Chess::~Chess()
{
    chess_t* temp = chess_head->next;
    while (temp != chess_head) {
        delete temp;
        temp = temp->next;
    }
    delete chess_head;
}

/* 
* 添加棋子，即下棋
* @param x:棋子横坐标
* @param y:棋子纵坐标
* @param color:棋子颜色
*/
void Chess::add_chess(int x, int y, ChessType color)
{
    chess_t* new_chess = new chess_t;
    new_chess->color = color;
    new_chess->x = x;
    new_chess->y = y;

    new_chess->next = chess_head->next;
    new_chess->pre = chess_head;

    chess_head->next = new_chess;
    new_chess->next->pre = new_chess;
}

/*
* 删除上一个棋子
* @param null
*/
void Chess::del_lastone_chess()
{
    if (chess_head->next == chess_head) {
        return; // 没有棋子可以删除
    }

    chess_t* last_chess = chess_head->next;
    chess_head->next = last_chess->next;
    last_chess->next->pre = chess_head;

    delete last_chess;
}

/*
* 删除全部棋子
* @param null
*/
void Chess::del_allchess()
{
    chess_t* temp = chess_head->next;
    while (temp != chess_head) {
        delete temp;
        temp = temp->next;
    }
    chess_head->next = chess_head;
    chess_head->pre = chess_head;
}

/*
* 获取上一个棋子 
* @param null
* @return chess_t *
*/
chess_t *Chess::get_last_chess()
{
    if (chess_head->next == chess_head) {
        return nullptr;
    }
    return chess_head->next;
}

/*
* 获取对应坐标的棋子
* @param x: 棋子的x坐标
* @param y: 棋子的y坐标
* @param color 棋子的颜色
* @return chess_t *
*/
chess_t *Chess::get_chess(int x, int y)
{
    chess_t* temp = chess_head->next;
    while (temp != chess_head) {
        
        if (temp->x == x && temp->y == y)
        {
            return temp;
        }

        temp = temp->next;
    }
    return nullptr;
}

/*
* 检测棋子颜色
* @param x: 棋子的x坐标
* @param y: 棋子的y坐标
* @param color 棋子的颜色
* @return ChessType
*/
bool Chess::check_chess_color(int x, int y, ChessType color)
{
    chess_t* temp = get_chess(x, y);
    if (temp == nullptr) {

        return (color == ChessNull) ? true : false;
    }
    return (temp->color == color) ? true : false;
}

/*
* 检测当前位置有没有棋子
* @param x: 棋子的x坐标
* @param y: 棋子的y坐标
* @return true or false 
*/
bool Chess::check_chess(int x, int y)
{
    chess_t* temp = get_chess(x, y);
    if (temp != nullptr) {
        return (temp->color == ChessNull) ? false : true;
    }
    return false;
}

/*
* 查找一个棋子颜色
* @param x: 棋子的x坐标
* @param y: 棋子的y坐标
* @return ChessType
*/
ChessType Chess::find_chess_color(int x, int y)
{
    chess_t* temp = get_chess(x, y);
    if (temp != nullptr) {
        return temp->color;
    }
    return ChessNull;
}

/*
 * 打印棋子
 */
void Chess::show_chess(chess_t *index)
{
    qDebug("x: %d, y: %d, color: %d", index->x, index->y, index->color );
}

/*
* 显示全部棋子信息
*/
void Chess::show_allChess()
{
    chess_t* temp = chess_head->next;
    while (temp != chess_head) {
        show_chess(temp);
        temp = temp->next;
    }
}
